<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" append-to-body width="80%">
      <div style="height: 80vh;overflow-x: auto;">
        <el-skeleton :rows="20" v-show="loading" />
        <create-sections title="基本信息" v-show="!loading">
          <el-form ref="rpForm" :model="fieldForm" :rules="fieldRules" :validate-on-rule-change="false" class="rp-form"
            inline label-position="top">
            <form-item-more v-for="(children, index) in columnList" :key="index" :field-from="fieldForm"
              :field-list="children" :ignore-fields="['']" @change="formChange">
              <template slot-scope="{ data }">
                <!-- <div>{{data.fieldName}}</div>
                <div v-if="data.fieldName == 'leadsName'">

                  
                  <business-info-input v-if="canUseEnterprise" v-model="fieldForm[data.field]" :maxlength="100"
                    :disabled="data.disabled" :debounce="1000" :type="data.formType" value-key="name"
                    @select="customerNameSelect" @input="formChange(data, index, $event)" />
                  <el-input v-else v-model.trim="fieldForm[data.field]" :disabled="data.disabled" maxlength="100"
                    :placeholder="data.placeholder" type="text" @input="formChange(data, index, $event)" />
                  <el-button type="text" :disabled="!businessInfo || businessInfo.name !== fieldForm[data.field]"
                    class="premiumInfoBtn" data-type="BusinessInformation" @click="checkBIDetail">
                    <i class="rp rp-icon-lightning-solid rp-premium-info-icon" data-type="BusinessInformation" />
                    <span class="rp-premium-info-label" data-type="BusinessInformation">工商信息</span>
                  </el-button>
                </div> -->
                <rp-relative-cell v-if="data && data.formType == 'customer' || data.formType == 'contacts'"
                  :value="fieldForm[data.field]" :disabled="data.disabled" :relative-type="data.formType"
                  @value-change="otherChange($event, data)" />

                <!-- <xh-business-status v-if="data && data.formType == 'business_type'" :value="fieldForm[data.field]"
                  :disabled="data.disabled" @value-change="otherChange($event, data)" />
                <xh-product v-if="data && data.formType == 'product'" :value="fieldForm[data.field]"
                  @value-change="otherChange($event, data)" /> -->
                <el-select v-if="data && data.formType == 'business_status'" v-model="fieldForm[data.field]"
                  :disabled="data.disabled" style="width: 100%;">
                  <el-option v-for="(item, index) in data.setting" :key="index" :label="item.name" :value="item.id" />
                </el-select>
              </template>
            </form-item-more>
            <AddTable v-if="isProduct == addType"/>
          </el-form>
        </create-sections>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="btnSubmit" v-if="isCopy==''">{{ dialogType == 2 || dialogType == 3 ? '提交审核' : '保 存' }}</el-button>
        <el-button type="primary" @click="btnSubmit(isCopy)" v-if="isCopy=='copy'">复制</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          v-if="(dialogType == 2 || dialogType == 3)">保存草稿</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import CreateSections from "@/components/CreateSections";
import RpRelativeCell from "@/components/CreateCom/RpRelativeCell.vue";
import FormItemMore from '@/components/busComponents/NewComponents/BusForm/FormItemMore'
import { isEmpty } from '@/utils/types'
import CustomFieldsMixin from '@/mixins/CustomFields'
import { queryFieldList, queryListHead } from "@/api/customer/common";
import { queryCustomerField } from "@/api/customer/customer";
import { queryProductField } from "@/api/product/product";
import BusinessInfoInput from '@/components/busComponents/BusinessInfo/Input'
import { addContacts, updateContacts, queryContactsField } from "@/api/contacts/contacts";//联系人
import { addContract, updateContract, queryContractField } from "@/api/contract/contract";//合同
import { addInvoice, updateInvoice, queryInvoiceField } from "@/api/invoice/invoice";//发票
import { queryCluesField } from "@/api/clue/clue";

import AddTable from '@/components/busComponents/NewComponents/AddTable'

export default {
  name: "addDialog",
  components: { CreateSections, FormItemMore, RpRelativeCell, BusinessInfoInput, AddTable },
  mixins: [CustomFieldsMixin],
  props: {
    dialogTitle: String,
    dialogType: Number,
    action: {
      type: Object,
      default: () => {
        return {
          type: "save",
          id: "",
          data: {},
        };
      },
    },
    addType: {
      type: String,
      default: '',
    },
  },
  watch: {
    addType (newVal, oldVal) {
      // console.log(oldVal)
      // console.log(newVal)
      this.queryFieldList();
    },
  },
  data () {
    return {
      dialogVisible: false,
      loading: false,
      baseFields: [],
      columnList: [],
      fieldForm: {},
      fieldRules: {},
      form: {
        name: '',
      },
      value: '',
      value1: '',
      // 工商信息
      businessInfo: null,
      businessInfoViewShow: false,
      noFieldsList: [],
      id: '',
      version: 0,
      batchId: '',
      isCopy:'',
      isProduct: this.$GlobalStatus.tableType.Product,
    };
  },
  computed: {
    ...mapGetters(['moduleData']),
    // 如果有次数就可以使用
    canUseEnterprise () {
      const enterprise = this.moduleData.find(item => item.module === 'enterprise')
      return enterprise ? enterprise.number > 0 : false
    },
    contactsSaveAuth () {
      return this.crm.contacts && this.crm.contacts.save
    },
    title () {
      return this.action.type === 'update' ? '编辑客户' : '新建客户'
    }
  },
  mounted () {
    // this.$nextTick(()=>{
    // const fatherDom = document.querySelector("body");
    //   if(fatherDom.append){
    //     fatherDom.append(this.$el);
    //   }else{
    //     fatherDom.appendChild(this.$el);
    //   }
    // })
  },
  methods: {
    otherChange (data, field) {
      if (field.formType === 'product') {
        this.fieldForm.money = data.value.totalPrice || ''
      }
      this.$set(this.fieldForm, field.field, data.value)
      this.$refs.crmForm.validateField(field.field)
    },
    formChange (field, index, value, valueList) {
      // if ([
      //   'select',
      //   'checkbox'
      // ].includes(field.formType) &&
      //     field.remark === 'options_type' &&
      //     field.optionsData) {
      //   const { fieldForm, fieldRules } = this.getFormContentByOptionsChange(this.fieldList, this.fieldForm)
      //   this.fieldForm = fieldForm
      //   this.fieldRules = fieldRules
      // }
    },
    cellClass ({ row, column, rowIndex, columnIndex }) {
      if (column.property === 'merchantNum') {
        return 'look--underline'
      } else {
        return ''
      }
    },
    addCustomer () {
      this.$refs.customerRelation.showRelationFun();
    },
    saveSuccess (data) {
      if (data.type == 'customer') {
        // this.handleHandle(data) ---刷新列表
        if (data.createContacts) {
          // this.createType = 'contacts'
          this.createShow = true
        }
      }
    },
    showFun (id, version, batchId,text) {
      this.dialogVisible = true;
      this.loading = true;
      // console.log(id)
      if(text){
        this.isCopy = text
      }
      if (id) {
        this.id = id;
        this.version = version;
        this.batchId = batchId;
        this.queryCustomerField();
      } else {
        this.queryFieldList();
      }
      this.queryListHead();
    },

    queryCustomerField () {
      // console.log(this.addType)
      let request = null;
      if (this.addType == this.$GlobalStatus.tableType.Contacts) {
        //联系人
        request = queryContactsField;
      } else if (this.addType == this.$GlobalStatus.tableType.Contract) {
        //合同
        request = queryContractField;
      } else if (this.addType == this.$GlobalStatus.tableType.Clue) {
        //线索
        request = queryCluesField;
      } else if (this.addType == this.$GlobalStatus.tableType.Product) {
        //线索
        request = queryProductField;
      } else {
        request = queryCustomerField;
      }
      request(this.id).then(res => {
          this.setInfoData(res.data);
          this.loading = false;
        }).catch(error => {
          this.loading = false;
        });

    },

    closeFun () {
      this.loading = false;
      this.dialogVisible = false;
    },
    closeLoading () {
      this.loading = false;
    },
    btnSubmit (text) {
      let params = {
        contactsId: this.addType,
        entity: this.fieldForm,
        field: this.noFieldsList,
      }
      // var keyValue = Object.entries(params.entity)
      params.field.forEach((fie) => {
        if (fie.formType == "customer" || fie.formType == "contacts") {
          if (params.entity[fie.fieldName].length > 0) {
            let id = params.entity[fie.fieldName][0].id;
            fie.value = Number.parseInt(id);
          } else {
            fie.value = undefined;
          }
        } else if (fie.fieldName == "specName") {
          params.specList = [];
        } else {
          fie.value = params.entity[fie.fieldName];
        }
        if (Object.prototype.toString.call(fie.value) === '[object Array]') {
          fie.value = fie.value.join(',');
        }
      })
      if (params.entity.superiorCustomerId && params.entity.superiorCustomerId.length > 0) {
        let superiorCustomerId = params.entity.superiorCustomerId[0].id;
        params.entity.superiorCustomerId = Number.parseInt(superiorCustomerId);
      } else {
        if (params.entity.superiorCustomerId) {
          params.entity.superiorCustomerId = '';
        }
      }
      //联系人相关
      if (params.entity.customerId && params.entity.customerId.length > 0) {
        let customerId = params.entity.customerId[0].id;
        params.entity.customerId = Number.parseInt(customerId);
      } else {
        if (params.entity.customerId) {
          params.entity.customerId = '';
        }
      }
      if (params.entity.parentContactsId && params.entity.parentContactsId.length > 0) {
        let parentContactsId = params.entity.parentContactsId[0].id;
        params.entity.parentContactsId = Number.parseInt(parentContactsId);
      } else {
        if (params.entity.parentContactsId) {
          params.entity.parentContactsId = '';
        }
      }

      let keys = Object.keys(params.entity);
      keys.forEach((fie) => {
        if (Object.prototype.toString.call(params.entity[fie]) === '[object Array]') {
          params.entity[fie] = params.entity[fie].join(',');
        }
      })
      if (this.id) {
        params.entity.id = this.id;
        params.entity.id = this.id;
        params.entity.batchId = this.batchId;
        params.entity.version = this.version;
      }
      this.loading = true;

      if (this.addType == this.$GlobalStatus.tableType.Contacts) {
        //联系人
        if (params.entity.id) {
          updateContacts(params).then(res => {
            this.closeFun();
          }).catch(error => {
            this.closeFun();
          })
        } else {
          addContacts(params).then(res => {
            this.closeFun();
          }).catch(error => {

          })
        }
        this.$emit("refreshList");
      } else if (this.addType == this.$GlobalStatus.tableType.Invoice) {
        //发票
        if (params.entity.id) {
          updateInvoice(params).then(res => {
            this.closeFun();
          }).catch(error => {
            this.closeFun();
          })
        } else {
          addInvoice(params).then(res => {
            this.closeFun();
          }).catch(error => {

          })
        }
        this.$emit("refreshList");
      } else if (this.addType == this.$GlobalStatus.tableType.Contract) {
        //合同
        if (params.entity.id) {
          if(text=='copy'){
            params.entity.num = ""
            addContract(params).then(res => {
              this.closeFun();
            }).catch(error => {

            })
          }else{
            updateContract(params).then(res => {
              this.closeFun();
            }).catch(error => {
              this.closeFun();
            })
          }
        } else {
          addContract(params).then(res => {
            this.closeFun();
          }).catch(error => {

          })
        }
        this.$emit("refreshList");
      } else {
        this.$emit("saveSubmit", params);
      }
    },

    queryFieldList () {
      this.loading = true;
      queryFieldList(this.addType).then(res => {
        console.log(res.data)
        this.setInfoData(res.data);
      }).catch(error => {
        this.loading = false;
      });
    },

    queryListHead () {
      console.log("www===4444444444444444===", this.addType)
      queryListHead(this.addType).then(res => {
        this.noFieldsList = res.data;
      }).catch(error => {
      });
    },

    setInfoData (data) {
      let list = data;
      const assistIds = this.getFormAssistIds(list)
      const baseFields = []
      const fieldList = []
      const fieldRules = {}
      const fieldForm = {}
      list.forEach(children => {
        const fields = []
        children.forEach(item => {
          const temp = this.getFormItemDefaultProperty(item)
          temp.show = !assistIds.includes(item.formAssistId)

          const canEdit = this.getItemIsCanEdit(item, this.action.type)
          // 是否能编辑权限
          if (temp.show && canEdit) {
            fieldRules[temp.field] = this.getRules(item)
          }

          // 是否可编辑
          temp.disabled = !canEdit

          // 特殊字段允许多选
          this.getItemRadio(item, temp)

          // 获取默认值
          if (temp.show) {
            fieldForm[temp.field] = this.getItemValue(item, this.action.data, this.action.type)
          }
          fields.push(temp)
          baseFields.push(item)
        })
        fieldList.push(fields)
      })
      this.baseFields = baseFields
      this.columnList = fieldList
      this.fieldForm = fieldForm
      this.fieldRules = fieldRules
      this.loading = false
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/custom-element.scss";

.div-flex {
  flex: 1;
  margin-right: 22px;
}

.add-customer {
  font-size: 16px;
  font-weight: 400;
  color: #204EC4;
  line-height: 36px;
  position: absolute;
  top: 0;
  right: 0;

}
</style>